<?php if(!defined('SIDELOADED')) { echo 'Direct access is not allowed.'; }
/**
 * @author Tyil <info@tyil.nl>
 * @version 1.0 beta [30-03-2012]
 */

if(Session::Get('user') > 0) {
  
  Website::View('page', array(
    'title' => 'Login',
    'content' => Website::View('login/already')
  ), true);
  
} else {

  if(@$_POST) {

    if(@$_POST['register'] == '1') {

      if(filled($_POST['email']) && filled($_POST['password']) && filled($_POST['password2']) && filled($_POST['username']) && filled($_POST['key'])) {
        // Check if everything is valid

        $db = new Database();
        $err = array();
        
        // Check for a valid key
        $db->Run('SELECT `key` FROM `users_regkeys` WHERE `key`="' . $db->Escape($_POST['key']) . '"');
        if($db->Rows() <= 0) { 
          
          $err['false_key'] = 'The registration key you have provided does not exist.';
          
        } else {
        
          // Check for a valid email
          if(!checkEmail($_POST['email'])) {

            $err['valid_email'] = 'You must specify a valid emailaddress';

          } else {

            // Check if the email address has been used
            $db->Run('SELECT `id` FROM `users` WHERE `email`="' . $db->Escape($_POST['email']) . '";');
            if($db->Rows() > 0) { $err['email_in_use'] = 'The emailaddress you tried to use is already in use.'; }

          }
        
          // Check if the passwords match
          if($_POST['password'] != $_POST['password2']) { $err['pass_match'] = 'The passwords you provided did not match.'; }
          
        }
        
        if(count($err) > 0) {
          
          Website::LoadFunction('listify');
          
          Website::View('page', array(
            'title' => 'Login',
            'preTitle' => Website::View('login/css'),
            'postTitle' => Website::View('login/js'),
            'content' => Website::View('login/form', array(
              'email' => @$_POST['email'],
              'username' => @$_POST['username'],
              'buttonCheck' => 1
            )),
            'error' => 'The following errors have occurred:' . listify($err)
          ), true);       
          
        } else {
          // No errors thus far, let's register the user!
          
          $id = User::Register($_POST['username'], $_POST['password'], $_POST['email'], $_POST['key']);
          
          Session::Set('user', $id);
          
          redirect(URL . '/members.html/' . $id);
          
        }
        
      } else {
        // Not everything was filled in

        Website::View('page', array(
          'title' => 'Login',
          'preTitle' => Website::View('login/css'),
          'postTitle' => Website::View('login/js'),
          'content' => Website::View('login/form', array(
            'email' => @$_POST['email'],
            'username' => @$_POST['username'],
            'buttonCheck' => 1
          )),
          'error' => 'You should fill out every field.'
        ), true);

      }

    } else {

      if(filled(@$_POST['email']) && filled(@$_POST['password'])) {
        // Check if the user's data was valid

        $db = new Database();

        $query = 'SELECT `id` FROM `users` WHERE `email`="' . $db->Escape($_POST['email']) . '";';
        $db->Run($query);
        $result = $db->Result();

        if($result !== false) {

          $user = new User($result->id);

          if(User::Hash($_POST['password'], $user->salt) == $user->password) {
            // Log the user in

            Session::Set('user', $user->id);

            Website::View('page', array(
              'title' => 'Home',
              'content' => Website::View('login/success'),
            ), true);

          } else {
            // Incorrect login credentials

            Website::View('page', array(
              'title' => 'Login',
              'preTitle' => Website::View('login/css'),
              'postTitle' => Website::View('login/js'),
              'content' => Website::View('login/form', array(
                'email' => @$_POST['email']
              )),
              'error' => 'Your login credentials were incorrect.'
            ), true);

          }

        } else {

          Website::View('page', array(
            'title' => 'Login',
            'preTitle' => Website::View('login/css'),
            'postTitle' => Website::View('login/js'),
            'content' => Website::View('login/form', array(
              'email' => @$_POST['email']
            )),
            'error' => 'Your login credentials were incorrect.'
          ), true);

        }

      } else {

        Website::View('page', array(
          'title' => 'Login',
          'preTitle' => Website::View('login/css'),
          'postTitle' => Website::View('login/js'),
          'content' => Website::View('login/form', array(
            'email' => @$_POST['email']
          )),
          'error' => 'Your login credentials were incorrect.'
        ), true);

      }

    }

  } else {

    Website::View('page', array(
      'title' => 'Login',
      'preTitle' => Website::View('login/css'),
      'postTitle' => Website::View('login/js'),
      'content' => Website::View('login/form', array(
        'email' => @${1}
      ))
    ), true);

  }
  
}
